package com.itheima.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.dto.UserDto;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean sendMsg(String phone) {
        // 1.生成验证码
        int number = new Random().nextInt(100000) + 100000;
        log.info("验证码:{}", number);
        // 2.将验证码写入Redis
        // 2.1Redis坐标依赖
        // 2.2检查Redis配置
        // 2.3启动本地的Redis服务
        // 2.4注入RedisTemplate
        // 2.5通过RedisTemplate.opsRorVale().set() 写入数据
        redisTemplate.opsForValue().set("CODE" + phone, number + "", 20L, TimeUnit.HOURS);
        // //另一种设置时间的方法
        //  redisTemplate.expire("", Duration.ofDays(2));
        // 3.发送验证码


        return true;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public UserVo login(UserDto userDto) {
        // 1.校验入参
        // 判空 hasText 里面用内容返回true
        if (userDto == null || !StringUtils.hasText(userDto.getCode()) || !StringUtils.hasText(userDto.getPhone())) {
            throw new RuntimeException("入参不能为空");
        }
        String phone = userDto.getPhone();
        String code = userDto.getCode();

        String redisCode = (String) redisTemplate.opsForValue().get("CODE" + phone);
        if (StringUtils.isEmpty(redisCode)) {
            throw new RuntimeException("验证码为空");
        }
        if (!redisCode.equals(code)) {
            throw new RuntimeException("验证码不正确");
        }


        User user = userMapper.findByPhone(phone);
        if (user == null) {
            // 5.1 组装user对象
            User newUser = new User();
            String id = IdUtil.getSnowflakeNextIdStr();
            newUser.setId(id);
            newUser.setName("用户{}" + System.currentTimeMillis());
            newUser.setPhone(phone);
            newUser.setSex("女");
            newUser.setIdNumber("");
            newUser.setAvatar("");
            newUser.setStatus(1);
            int add = userMapper.add(newUser);
            if (add != 1) {
                throw new RuntimeException("新用户注册失败");
            }
            user = new User();
            BeanUtils.copyProperties(newUser, user);
        }
        String token = "user_token" + System.currentTimeMillis() + user.getId();
        log.info("生成的token是:{}", token);
        redisTemplate.opsForValue().set("user_token:" + token, JSON.toJSONString(user),20L, TimeUnit.HOURS);


        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user, userVo);
        userVo.setToken(token);
        return userVo;
    }

    /**
     * 判断手机号码是否存在是返回true
     *
     * @param phone
     * @return
     */
    @Override
    public boolean isExistPhone(String phone) {
        User user = findByPhone(phone);
        if (user == null) {
            return false;
        }
        return true;
    }


    @Override
    public boolean add(UserDto userDto) {
        String phone = userDto.getPhone();
        User newUser = new User();
        String id = IdUtil.getSnowflakeNextIdStr();
        newUser.setId(id);
        newUser.setName("用户{}" + System.currentTimeMillis());
        newUser.setPhone(phone);
        newUser.setSex("女");
        newUser.setIdNumber("");
        newUser.setAvatar("");
        newUser.setStatus(1);
        int add = userMapper.add(newUser);
        return add > 0;
    }

    @Override
    public void clearToken(String token) {

        Boolean res = redisTemplate.hasKey("user_token:" + token);
        if (res){
            redisTemplate.delete("user_token:" + token);
        }
    }

    /**
     * 按id号查找查找用户
     */
    @Override
    public User findById(String id) {
        User user = userMapper.findById(id);
        return user;
    }

    /**
     * 按手机号查找查找用户
     */
    public User findByPhone(String id) {
        User user = userMapper.findByPhone(id);
        return user;
    }
}
